<script lang="ts" setup>
  import { LoadingOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons-vue'
  import { message, Upload } from 'ant-design-vue'
  import { v4 as uuidv4 } from 'uuid'
  import { onMounted, reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { getDataProductById, saveDataProduct } from '/@/api/exchange/dataProduct'
  import { getDictList, uploadFileList } from '/@/api/exchange/requirement'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getToken } from '/@/storage'

  import { dataLimitList, dataTypeList } from '../requirement/data'
  import RelevanceRequire from './components/RelevanceRequire.vue'
  import SelectUploadData from './components/SelectUploadData.vue'

  /** 基础数据 */
  const router = useRouter()
  const route = useRoute()
  const id = route.query && route.query.id ? route.query.id : null
  const token = getToken() || ''
  const uploadApi = `${import.meta.env.VITE_BASE_API_PATH}/contentFile/upload/V1`
  const dictList = ref<RequirementTypes.DictValueResponse[]>([])
  const dictObj = ref<RequirementTypes.StateData>()
  const logoLoading = ref(false)
  const loading = ref(false)
  const submitLoading = ref(false)
  const saveLoading = ref(false)
  const RelevanceRef = ref<InstanceType<typeof RelevanceRequire>>()
  const SelectRef = ref<InstanceType<typeof SelectUploadData>>()
  const productRequires = ref<DataProductTypes.RequirePageVOSType[]>([])
  const licenseObj = reactive({ 1: 'SSC-DA-O-1', 2: 'SSC-DA-NC-1' })
  /** 表单数据 */
  const formRef = ref()
  const labelCol = { span: 3 }
  const wrapperCol = { span: 21 }
  const formState = reactive({
    productName: '',
    dataType: undefined,
    uploadType: null,
    productType: null,
    dictResults: null,
    dictResultValue: [],
    productBrief: '',
    productDetail: '',
    productLogo: '',
    downloadFlag: null,
    pricingType: null,
    priceAmount: null,
    coinType: null,
    license: null,
    dataMarketFileVOS: [],
    productRequires: [],
    publicStatus: null,
  })
  const rules: Record<string, Rule[]> = {
    productName: [{ required: true, message: '请输入标题', trigger: 'change' }],
    dataType: [{ required: true, message: '请选择数据类型', trigger: 'change' }],
    productBrief: [{ required: true, message: '请输入产品简介', trigger: 'change' }],
    license: [{ required: true, message: '请选择许可', trigger: 'change' }],
    isPermission: [{ required: true, message: '请阅读许可内容', trigger: 'change' }],
  }
  const permissionObj = reactive({
    '1': '许可一',
    '2': '许可二',
    '3': '许可三',
  })

  /** 上传logo */
  const beforeUploadLogo = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 5
    const isType = ['.jpg', '.jpeg', '.png'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isType) {
      message.error('不支持的格式文件')
      return false
    } else if (!isLt2M) {
      message.error('文件大小超过5MB，请选择一个较小的文件。')
      return false
    } else {
      return true
    }
  }
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      logoLoading.value = true
      return
    }
    if (info.file.status === 'done') {
      message.success('上传成功')
      formState.productLogo = info.file.response.responseData
      logoLoading.value = false
    }
    if (info.file.status === 'error') {
      logoLoading.value = false
      message.error(info.file.response.responseMessage || '上传错误')
    }
  }

  // 上传文件
  const beforeUpload = (file) => {
    console.log('\n\n---file', file)
    const { name } = file
    const fileExtension = name.split('.').pop()
    const newFileName = `${uuidv4()}.${fileExtension}` // 生成新的文件名，包含UUID和原文件扩展名
    const params = {
      file,
      name: newFileName,
      isDirectory: false,
      currentDir: '/',
      description: '',
      directoryType: 'FILE',
    }
    uploadFile(params)
    return false
  }
  const handleRemove = (index) => {
    formState.dataMarketFileVOS.splice(index, 1)
  }
  const uploadFile = async (params) => {
    loading.value = true
    const { responseCode, responseData } = await uploadFileList(params)
    if (responseCode === 100000000) {
      const { file } = params
      formState.dataMarketFileVOS.push({
        fileId: responseData.data,
        fileName: file.name,
        fileType: file.type,
        fileSize: file.size,
        fileUrl: file.uid,
      })
      message.success('上传成功')
      loading.value = false
    } else {
      message.error('上传失败')
      loading.value = false
    }
  }

  /** 添加数据、关联需求 */
  const showModale = (type: string) => {
    if (type === 'relevance') {
      RelevanceRef.value?.showModal()
      RelevanceRef.value?.getData()
    } else {
      SelectRef.value?.showModal()
      SelectRef.value?.getData()
    }
  }
  /** 获取关联需求 */
  const getRelevanceList = (list: RequirementTypes.IResponse[]) => {
    productRequires.value = JSON.parse(JSON.stringify(list))
  }
  /** 删除关联需求 */
  const deleteRelevance = (index: number) => {
    productRequires.value.splice(index, 1)
  }

  /** 获取已有数据 */
  const getSelectList = (list: RequirementTypes.IResponse[]) => {
    formState.dataMarketFileVOS = list
  }

  /** 选择类别 */
  const dictData = () => {
    let list = []
    formState.dictResultValue.map((item) => {
      console.log('item', item)
      list.push({
        code: item.key,
        name: typeof item.label === 'string' ? item.label : item.label[0].children,
      })
    })
    return {
      values: list,
      typeCode: dictObj.value.typeCode,
      typeName: dictObj.value.typeName,
    }
  }

  // 读许可内容
  const readPermission = () => {
    if (!formState.license) {
      message.error('请选择许可')
      return
    }
    const ageUrl = router.resolve({
      path: '/license',
      query: { id: formState.license },
    })
    window.open(ageUrl.href, '_blank')
    formState.isPermission = true
  }

  /** 表单提交（保存、上架） */
  const onSubmit = (state: number) => {
    formRef.value
      .validate()
      .then((values) => {
        if (state === 1) {
          saveLoading.value = true
        } else {
          submitLoading.value = true
        }
        console.log('\n\n---values---', values)
        const params = {
          ...values,
          ...{
            status: state,
          },
        }
        if (id - 0 !== 0) {
          params.id = id
        }
        if (formState.dictResultValue && formState.dictResultValue.length) {
          params.dictResults = dictData()
        }
        if (productRequires.value.length) {
          params.productRequires = productRequires.value
        }
        delete params.dictResultValue
        console.log('\n\n---params---', params)
        onSaveDataProduct(params)
      })
      .catch((error) => {
        console.log('error', error)
      })
  }

  const onSaveDataProduct = async (params: DataProductTypes.SaveRequest) => {
    const { responseCode } = await saveDataProduct(params)
    if (responseCode === 100000000) {
      message.success('保存成功')
      pageBack()
    }
    saveLoading.value = false
    submitLoading.value = false
  }

  /**回退页面*/
  const pageBack = () => {
    router.back()
  }

  /**获取字典*/
  const getDictData = async () => {
    const params = { type: 'customer_require_type' }
    const { responseData } = await getDictList(params)
    if (responseData) {
      dictObj.value = {
        typeCode: responseData.typeCode,
        typeName: responseData.typeName,
      }
      dictList.value = responseData.values || []
    }
  }

  // 获取详情信息
  const getDataProductDetail = async () => {
    const { responseCode, responseData } = await getDataProductById({ dataProductId: id })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      Object.assign(formState, responseData)
      initFileList(responseData)
    }
    console.log('\n\n---formState---', formState)
  }
  // 初始化表单数据
  const initFileList = (responseData) => {
    if (responseData.customerDataRecordPageVOS && responseData.customerDataRecordPageVOS.length) {
      responseData.customerDataRecordPageVOS.map((item) => {
        const detail = item.fileDetail ? JSON.parse(item.fileDetail) : {}
        formState.dataMarketFileVOS.push(detail)
      })
    }
    if (responseData.productRequirePageVOS && responseData.productRequirePageVOS.length) {
      responseData.productRequirePageVOS.map((item) => {
        productRequires.value.push(item)
      })
    }
    if (responseData.dictResults && responseData.dictResults.values.length) {
      responseData.dictResults.values.map((item) => {
        formState.dictResultValue.push({
          key: item.code,
          label: item.name,
        })
      })
    }
  }

  onMounted(() => {
    if (id - 0 !== 0) {
      getDataProductDetail()
      formState.isPermission = true
    }
    getDictData()
  })
</script>

<template>
  <div class="add">
    <div class="header">数据产品-{{ id - 0 !== 0 ? '编辑' : '新增' }}</div>
    <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="产品名称" name="productName">
        <a-input v-model:value="formState.productName" style="width: 400px" :maxlength="20" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="数据类型" name="dataType">
        <a-select v-model:value="formState.dataType" placeholder="请选择" style="width: 400px">
          <a-select-option v-for="item in dataTypeList" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="上传方式" name="uploadType">
        <a-radio-group v-model:value="formState.uploadType">
          <a-radio :value="1">手动上传</a-radio>
          <a-radio :value="2">选择已有数据</a-radio>
        </a-radio-group>
        <template v-if="formState.uploadType">
          <a-form-item label="" name="dataMarketFileVOS" v-if="formState.uploadType === 1" class="create-order-select">
            <a-upload :show-upload-list="false" :before-upload="beforeUpload">
              <a-button :loading="loading" type="primary">
                <upload-outlined v-if="!loading" />
                上传
              </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item label="" name="dataMarketFileVOS" v-else class="create-order-select">
            <a-button type="primary" @click="showModale('select')">选择</a-button>
          </a-form-item>
          <div v-for="(item, index) in formState.dataMarketFileVOS" :key="item.fileId">
            <text style="padding-right: 20px">{{ item.fileName }}</text>
            <a @click="handleRemove(index)">删除</a>
          </div>
        </template>
      </a-form-item>
      <a-form-item label="数据分类" name="dictResultValue">
        <a-select v-model:value="formState.dictResultValue" placeholder="请选择" style="width: 400px" :labelInValue="true" mode="multiple">
          <a-select-option v-for="item in dictList" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="产品简介" name="productBrief">
        <a-textarea v-model:value="formState.productBrief" style="width: 400px" :maxlength="200" placeholder="请输入" allow-clear />
      </a-form-item>
      <a-form-item label="产品详情描述" name="productDetail">
        <a-textarea v-model:value="formState.productDetail" style="width: 400px" :maxlength="200" placeholder="请输入" allow-clear />
      </a-form-item>
      <a-form-item label="产品logo" name="productLogo">
        <a-upload name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :show-upload-list="false" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUploadLogo" @change="handleChange">
          <img v-if="formState.productLogo" :src="formState.productLogo" alt="avatar" class="logo-img" />
          <div v-else>
            <loading-outlined v-if="logoLoading" />
            <plus-outlined v-else />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="是否可下载" name="downloadFlag">
        <a-radio-group v-model:value="formState.downloadFlag">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="关联需求" name="productRequires">
        <a-button type="primary" @click="showModale('relevance')">添加</a-button>
        <div v-if="productRequires && productRequires.length" style="margin-top: 10px">
          <a-tag class="label-item" color="blue" closable @close="deleteRelevance(index)" v-for="(item, index) in productRequires" :key="item.requireId">{{ item.requireName }}</a-tag>
        </div>
      </a-form-item>
      <a-form-item label="是否市场公开" name="publicStatus">
        <a-radio-group v-model:value="formState.publicStatus">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="2">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="定价方式" name="pricingType">
        <a-radio-group v-model:value="formState.pricingType">
          <a-radio :value="1">一口价</a-radio>
          <a-radio :value="2">单价</a-radio>
          <a-radio :value="3">面议</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="积分" name="priceAmount">
        <a-input v-model:value="formState.priceAmount" style="width: 400px" :maxlength="20" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="许可" name="license">
        <a-radio-group v-model:value="formState.license">
          <a-radio value="1">许可一</a-radio>
          <a-radio value="2">许可二</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="许可内容" name="isPermission">
        <a @click="readPermission">{{ formState.license ? licenseObj[formState.license] : '暂无' }}</a>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 3 }" class="bottom-btn">
        <a-button type="primary" @click="onSubmit(1)" :loading="saveLoading">保存</a-button>
        <a-button type="primary" class="back-btn" @click="onSubmit(2)" :loading="submitLoading">提交申请</a-button>
        <a-button class="back-btn" @click="pageBack()">返回</a-button>
      </a-form-item>
    </a-form>

    <RelevanceRequire ref="RelevanceRef" :selectList="productRequires" @back="pageBack" @get-relevance-list="getRelevanceList" />
    <SelectUploadData ref="SelectRef" :selectList="formState.dataMarketFileVOS" @back="pageBack" @get-select-list="getSelectList" />
  </div>
</template>

<style lang="less" scoped>
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;

    .logo-img {
      width: 100%;
      height: 100%;
    }
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .add {
    width: 100%;
    padding: 0 24px 30px;
    background: #fff;
    border-radius: 2px;

    .header {
      width: 100%;
      height: 64px;
      margin-bottom: 20px;
      border-bottom: 1px solid #f2f3f5;
      font-size: 16px;
      font-weight: bold;
      color: #000;
      line-height: 64px;
    }

    .create-title {
      padding-left: 20px;
      margin-bottom: 10px;
      font-size: 16px;
      color: #000;
    }

    .create-order-select {
      margin-top: 20px;
    }

    .back-btn {
      margin-left: 20px;
    }

    .label-box {
      width: 100%;
      display: flex;
      align-items: center;

      .label-btn {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: #08979c;
        text-align: center;
        font-size: 24px;
        line-height: 32px;
        color: #fff;
        cursor: pointer;
      }

      .label-btn,
      .label-list {
        margin-left: 20px;
      }

      .label-item {
        margin-right: 10px;
      }
    }

    .bottom-btn {
      border-top: 1px solid #d9d9d9;
      padding-top: 30px;
    }
  }
</style>
